package com.wteam.dragon.system.apps.server.service.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wteam.dragon.system.apps.server.povo.bean.Email;
import com.wteam.dragon.system.apps.server.mapper.EmailMapper;
import com.wteam.dragon.system.apps.server.service.EmailService;
import com.wteam.dragon.system.apps.server.povo.vo.SendEmailVo;
import com.wteam.dragon.system.basebean.bean.ResultMessage;
import com.wteam.dragon.system.exception.BadRequestException;
import com.wteam.dragon.system.apps.security.utils.EncryptUtils;
import com.wteam.dragon.system.util.StringUtils;
import com.wteam.dragon.system.util.ValidationUtil;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * @Author 陈晓辉
 * @Date 2020/3/23
 */
@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {
    private final EmailMapper emailMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage addEmail(Email email) {
        if(!StringUtils.isBlank(email.getPassword())){
            try {
                email.setPassword(EncryptUtils.desEncrypt(email.getPassword()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        emailMapper.insert(email);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setStatus(HttpStatus.OK.value());
        resultMessage.setMessage("添加成功");
        return resultMessage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage deleteEmail(Long id) {
        emailMapper.deleteById(id);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setStatus(HttpStatus.OK.value());
        resultMessage.setMessage("删除成功");
        return resultMessage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage updateEmail(Email email) {
        if(!StringUtils.isBlank(email.getPassword())){
            try {
                email.setPassword(EncryptUtils.desEncrypt(email.getPassword()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        emailMapper.updateById(email);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setStatus(HttpStatus.OK.value());
        resultMessage.setMessage("更新成功");
        return resultMessage;
    }

    @Override
    public ResultMessage getEmailList() {
        QueryWrapper<Email> emailQueryWrapper = new QueryWrapper<>();
        List<Email> emailList = emailMapper.selectList(emailQueryWrapper);
        Dict resultMap = Dict.create()
                .set("message", "请求成功")
                .set("emailList",emailList);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setStatus(HttpStatus.OK.value());
        resultMessage.setResultParam(resultMap);
        return resultMessage;
    }

    @Override
    public ResultMessage sendEmail(Email email, SendEmailVo sendEmailVo) {
        if(email == null){
            throw new BadRequestException("请先配置，再操作");
        }
        // 封装
        MailAccount account = new MailAccount();
        account.setHost(email.getHost());
        account.setPort(Integer.parseInt(email.getPort()));
        account.setAuth(true);
        try {
            // 对称解密
            account.setPass(EncryptUtils.desDecrypt(email.getPassword()));
        } catch (Exception e) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BadRequestException(e.getMessage());
        }
        account.setFrom(email.getUser()+"<"+email.getFormUser()+">");
        // ssl方式发送
        account.setSslEnable(true);
        String content = sendEmailVo.getContent();
        int size = sendEmailVo.getTos().size();
        Mail.create(account)
                .setTos(sendEmailVo.getTos().toArray(new String[size]))
                .setTitle(sendEmailVo.getSubject())
                .setContent(content)
                .setHtml(true)
                //关闭session
                .setUseGlobalSession(false)
                .send();
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setStatus(HttpStatus.OK.value());
        resultMessage.setMessage("发送邮件成功");
        return resultMessage;
    }
}
